<template>
	<view class="index">
		<view class="header">
			<view class="left"><text>退出</text></view>
			<view class="center">默认聊天室（{{online}}）</view>
			<view class="right"><u-icon name="scan" size="50" @click="scanCode" class="scan"></u-icon></view>
		</view>
		<view class="main">
			<scroll-view class="content"
				scroll-y="true" 
				:scroll-top="scrollTop"
			 	:scroll-with-animation="true"
			 >
					 
				<view class="msg-line sys-msg">
					<view class="times">
						2020-02-22 12:20:59
					</view>
					<view class="msg-content">
						<text>欢迎登陆聊天室</text>
					</view>
				</view>
				
				 <view class="msg-line me-msg">
					<view class="name">
						张三
						<text class="times">
							(2020-12-12 16:55:02)
						</text>
					</view>
					<view class="msg-content">
						你好李四，我是张三，请介绍一下你自己！
					</view>
				</view>
				
				<view class="msg-line you-msg">
					<view class="name">
						李四
						<text class="times">
							(2020-12-12 16:55:05)
						</text>
					</view>
					
					<view class="msg-content">
						你好张三，我是李四，很高兴认识你！
					</view>
				</view>
				
				
				
				<template v-for="(item,index) in msgBox" >
					
					<!-- 系统消息 -->
					<view class="msg-line sys-msg" v-if="item.cmdType == 0" :key="index">
						<view class="times">
							{{item.sendTime}}
						</view>
						<view class="msg-content">
							<text v-html="item.msg"></text>
						</view>
					</view>
					
					
					<!-- 自己发送的消息 -->
					 <view class="msg-line me-msg" :key="index" v-if="item.cmdType == 1">
						<view class="name">
							{{item.sender}}
							<text class="times">
								({{item.sendTime}})
							</text>
						</view>
						<view class="msg-content" v-html="item.msg"></view>
					</view>
					
					<!-- 好友发送的消息 -->
					<view class="msg-line you-msg" :key="index" v-if="item.cmdType == 2">
						<view class="name">
							{{item.sender}}
							<text class="times">
								{{item.sendTime}}
							</text>
						</view>
						
						<view class="msg-content"  v-html="item.msg"></view>
					</view>
				</template>
			</scroll-view>
			
			<view class="input-box">
				<view class="container">
					<view class="left"><view class="iconfont icon-add-o"></view></view>
					<view class="input">
						<view class="text-box">
							<u-input v-model="sendEntity.text" type="text" :clearable="false" placeholder="" />
						</view>
					</view>
					<view class="btn-groups">
						<view style="margin-top:11upx;">
							<view class="bq-icon" style="display: inline-block;">
								<view class="iconfont icon-biaoqing_3" @click="bqBox.show = true"></view>
								</view>
			
							<view class="send-btn" style="display: inline-block;position: relative;top: -15upx;left: 2upx;transform: scale(.9);">
								<u-button type="success" @click="sendMsg">发送</u-button>
								</view>
						</view>
					</view>
				</view>
				<view class="bq-container" v-show="true">
					<view style="background-color: #A71D5D;">
						<image src="../../static/bq/1.gif" mode=""></image>
					</view>
				</view>
			</view>
		</view>
		
		
		<u-modal 
			ref="uModal"
			v-model="namesModel.show" 
			title="设置您的名称"
			confirm-text="确认设置"
			async-close
			@confirm="setNameClick"
		>
			<view class="modal_content">
				<view class="title">
					请在下方输入名称：
				</view>
				<view class="content">
					<u-input v-model="namesModel.name" type="text" border placeholder="请输入名称"/>
				</view>
			</view>
			
		</u-modal>
		
		<u-toast ref="uToast" />
		
		<u-modal v-model="scanLoginModel.show"
		@confirm="loginConfim(true)"
		@cancel="loginConfim(false)"
		show-cancel-button
		class="login-model"
		 title="登陆确认">
			<view class="content">
				您正在进行扫码登录，是否允许此操作？
			</view>
		</u-modal>
	</view>
</template>

<script>
import {LoginUtil} from '@/utils/index.js'
import MessageHandler,{Event} from '../../utils/MessageEventHandler.js'
export default {
	name: 'index',
	data() {
		return {
			scanLoginModel:{
				show:false,
			},
			sendEntity: {
				
			},
			msgBox:[],
			online:0,
			bqBox:{
				show:false
			},
			socketEntity:{
				task:null,
				isConnec:false,
			},
			namesModel:{
				show:false
			},
			scrollTop:0,
			heartInterval:null
		}
	},

	async onLoad() {
			
		const token = LoginUtil.getToken();
		if(!token||token.trim().length==0){
			uni.redirectTo({
				url:"../Login/Login"
			})
		}
		const userInfo_res = await this.$server.user.getUserInfo();
		console.log('uir',userInfo_res);
		
		let isInit = true;
		
		let name = userInfo_res.data.data.name;
		if(!userInfo_res.data.data||!userInfo_res.data.data.name){
			isInit = false;
			// 让用户输入用户名 并保存
			this.namesModel.show = true;
			
		}
		
		if(isInit){
			 this.initScoket(name);
		}
		
	},
	methods: { 
		scanCode(){
			const $t = this;
			uni.scanCode({
				onlyFromCamera:true,
				scanType:["qr"],
				success(res) {
					const index = res.result.indexOf(":=");
					console.log(res.result)
					if(index != -1){
						const d = JSON.parse(res.result.substring(index+2));
						
						$t.$server.qrcode.scanCode(d.channelId).then(res=>{
							const {data} = res;
							if(data.code == 200){
								$t.scanLoginConfim(d.channelId);
							}
						})
					}
				}
			})
		},
		// 发送消息
		sendMsg(){
			const $t = this;
			if(!this.sendEntity.text||this.sendEntity.text.length === 0){
				   $t.$refs.uToast.show({
					title: "发送内容不能为空",
					position:"top",
					type: 'warning'
				   })
				  return;
			  }
			 let msg={
			   cmdType:2,
			   msg:this.sendEntity.text 
			 };
			this.socketEntity.task.send({data:JSON.stringify(msg),success:()=>{
				$t.sendEntity.text="";
			}});
			
		},
		setNameClick(){
			const $t = this;
			const _name = this.namesModel.name;
			console.log(_name)
			this.$server.user.setUserName(_name).then(res=>{
				const {data} = res;
				console.log(data)
				$t.$refs.uModal.clearLoading();
				if(data.code == 200){
					$t.namesModel.show=false;
					$t.namesModel.name="";
					
					$t.$refs.uToast.show({
						title: "设置完成",
						position:"top",
						type: 'success'
					})
					
					$t.initScoket(_name);
				}else{
					console.log($t.$refs);
					$t.$refs.uToast.show({
						title: data.msg,
						position:"top",
						type: 'warning'
					})
				}
			}).catch(err=>console.error(err))
			
		},
		initScoket(name){
			const  $t = this;
			const mhandler = new MessageHandler();
			mhandler.registeEvent(Event.FLUSH_MESSAGE,this.renderMsg)
			mhandler.registeEvent(Event.FLUSH_ONLINE,this.reflushOnline)
			
			
			this.socketEntity.task = uni.connectSocket({
			    url:  this.$server.getWsUrl(), //仅为示例，并非真实接口地址。
			    complete: ()=> {}
			});
			
			this.socketEntity.task.onOpen(res=>{
				this.socketEntity.isConnec = true;
				console.log("连接成功",res)
				
				var cmdData = {
					cmdType:1,
					name:name
				  }
				  uni.sendSocketMessage({
				  	data:JSON.stringify(cmdData)
				  });
				 
				 $t.initHeartInterval({
					 send(msg){
						  uni.sendSocketMessage({
							  data:msg
						  })
					 }
				 }); 
				  
			})
			this.socketEntity.task.onClose(function(){
				$t.clearHeartInterval();
			})
			
			this.socketEntity.task.onError(function(err){
					console.log("连接失败",err)
			})
			
			this.socketEntity.task.onMessage((res)=>{
				const msg = JSON.parse(res.data)
				mhandler.handle(msg)
			})
			
		},
		initHeartInterval(ws){
			this.clearHeartInterval();
			
			this.heartInterval = setInterval(()=>{
				try{
					ws.send(JSON.stringify({cmdType:101}))
				}catch(e){
					//TODO handle the exception
					this.clearHeartInterval();
				}
			},7000);
		},
		clearHeartInterval(){
			if(this.heartInterval){
				clearInterval(this.heartInterval);
				this.heartInterval = null;
			}
		},
		renderMsg(msg){
			console.log('渲染消息：',msg)
			
			this.formatMessage(msg); 
			this.msgBox.push(msg)
			
			this.$nextTick(function(){
				this.scrollTop=0
			})
		},
		reflushOnline(msg){
			console.log('刷新在线人数：',msg)
			this.online = msg.online;
		},
		scanLoginConfim(channelId){
			this.scanLoginModel.show=true;
			this.scanLoginModel.channelId = channelId;
		},
		loginConfim(accept){
			const entity = {
				channelId:this.scanLoginModel.channelId,
				accept:accept
			} 
			
			this.$server.qrcode.confim(entity).then(res=>{
				const {data} = res;
				if(data == 200){
					this.scanLoginModel.show=false;
					this.scanLoginModel.channelId="";
				}
			});
		},
		  formatMessage(msgObj) {
		      let reg1 = /\[&bq#(\d{1,3})\]/gim;
		      let msg = "";
		
		      let start = 0;
		      let res;
		      while (true) {
		        res = reg1.exec(msgObj.msg);
		        if (res == null) {
		          break;
		        }
		        msg += msgObj.msg.substring(start, res.index);
		         let IMG = require(`../../static/bq/${res[1]}.gif`);
		        msg += `<image src="${IMG}" />`;
	
				console.log(IMG)
		        start = res[0].length + res.index;
		      }
		
		      if (start < msgObj.msg.length) {
		        msg += msgObj.msg.substring(start);
		      }
		
		      msgObj.msg = msg;
		    }
	}
};
</script>

<style lang="scss">
@import '@/static/font_2379421/iconfont.css';
.index {
	position: relative;
	width: 100%;
	height: 100vh;
	overflow: hidden;
	.header {
		display: block;
		height: 140upx;
		width: 100%;
		position: relative;
		background-color: #18b566;
		padding: 20upx;
		padding-top: 80upx;
		color: #ffffff;
		.left {
			float: left;
			max-width: 200upx;
			height: inherit;
		}
		.center {
			height: inherit;
			position: absolute;
			left: 200upx;
			right: 200upx;
			text-align: center;
		}
		.right {
			float: right;
			max-width: 200upx;
			height: inherit;
		}
	}

	.main{
		width: 100%;
		height: calc(100vh - 140upx);
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		
		.msg-line{
			display: block;
			padding-top: 20upx;
			width: 100%;
			min-height: 20upx;
			&.sys-msg{
				text-align: center;
				.times{
					font-size: 20upx;
					color: #4b4d50;
				}
				.msg-content{
					display: inline-block;
					height:50upx;
					line-height: 50upx;
					background-color: rgba($color: #000000, $alpha: .1);
					border-radius: 50upx;
					padding: 0 25upx;
					color: #2c2c2c;
				}
			}
			
			&.me-msg{
				text-align: right;
				padding-right: 15upx;
				.name{
					color: #2B85E4;
					text-shadow: 0 0 2upx rgba($color: #000000, $alpha: .2);
					
					.times{
						color: #6f6f6e;
						font-size: 26upx;
					}
				}
				
				.msg-content{
					margin-top: 10upx;
					display: inline-block;
					max-width: 440upx;
					padding: 16upx;
					min-height: 15upx;
					word-break: break-word;
					background-color: #17ba60;
					border-radius: 15upx;
					text-align: left;
					min-width: 200upx;
					box-shadow: 0 0 4upx rgba($color: #000000, $alpha: .1);
				}
			}
			
			&.you-msg{
				text-align: left;
				padding-left: 15upx;
				.name{
					color: #4752e4;
					text-shadow: 0 0 2upx rgba($color: #000000, $alpha: .3);
					
					.times{
						color: #6f6f6e;
						font-size: 26upx;
					}
				}
				
				.msg-content{
					margin-top: 10upx;
					display: inline-block;
					max-width: 440upx;
					min-width: 200upx;
					padding: 16upx;
					min-height: 15upx;
					word-break: break-word;
					background-color: #efefef;
					border-radius: 15upx;
					text-align: left;
					box-shadow: 0 0 4upx rgba($color: #000000, $alpha: .1);
				}
			}
		}
		
		.content {
			display: block;
			background-color: #e8e8e8;
			flex: 1;
			width: 100%;
			position: absolute;
			top: 140upx;
			bottom: 120upx;
			padding: 15upx 2upx;
		}
		
		.input-box {
			border-top: 1px solid rgba($color: #000000, $alpha: .1);
			position: absolute;
			height: 120upx;
			width: 100%;
			bottom: 0;
			background-color: #e9e7e7;
			.container {
				width: 100%;
				height: inherit;
				position: relative;
				display: flex;
				flex-direction: row;
				justify-content: flex-start;
				.left {
					flex: 1;
					.iconfont {
						font-size: 70upx;
						font-weight: 500;
					}
					padding: 20upx;
				}
				.input {
					flex: 6;
					padding-right: 10upx;
					.text-box {
						margin-top: 15upx;
						padding: 5upx 15upx;
						background-color: #ffffff;
						border-radius: 5px;
						height: 80upx;
					}
				}
				.btn-groups {
					flex: 3;
					padding: 5upx;
		
					.bq-icon {
						.iconfont {
							font-size: 70upx;
							font-weight: 500;
						}
					}
				}
			}
		}
	}
	
	.modal_content{
		padding: 60upx;
		display: block;
		position: relative;
		.title{
			margin-bottom:20upx
		}
	}
	
	.login-model{
		.content{
			padding: 50upx 70upx;
		}
	}
	
}


</style>
